# importing required modules
import os, time, shutil
from pathlib import Path

# from ntpath import join


class folder_dir:
    '文件基类'

    def _init_(self):
        self.new_Path = ""  # 压缩后新路径，后期需加上压缩日期"_230116092345.7z"
        self.root = ""
        self.Temp_path = ""  # 临时放置用以压缩的文件路径，与新路径相差一个层级

    def oldcheck(self):
        if self.m_time > 0:
            return True


def get_all_folder(dir):
    """列出所有时间符合日期的文件夹，并将其按照时间分类、剪切至临时文件夹

    Args:
        dir (_type_): 扫描文件路径：D:\Gen6 Test Result\BH_assy

    Returns:
        folder_lis(folder_dir[]): 包含文件信息的列表
    """
    folder_lis = []
    # list all producttype folder
    i = 0  # to control the
    i_max = 20  # max number to move
    folder_FB = os.listdir(dir + r'\Reporting')  # 列出front/back
    daytoday = time.gmtime(time.time())  # 获取当前时间
    for folder_ffbb in folder_FB:
        if i > i_max - 1:
            break
        path_FB = os.path.join(dir + r'\Reporting', folder_ffbb)
        if os.path.isdir(path_FB):
            folder_T = os.listdir(path_FB)
            for folder_tt in folder_T:
                if i > i_max - 1:
                    break
                Name_split = folder_tt.split(
                    "_"
                )  # 7_HKMC_SVS_Front ->[7,HKMC,SVS,Front]
                NS_len = len(Name_split)  # 4
                Name_Type = "_".join(Name_split[1 : NS_len - 1])  # HKMC_SVS
                Name_FB = Name_split[NS_len - 1]  # Front
                path_T = os.path.join(
                    path_FB, folder_tt
                )  # ~\BH_assy\Reporting\0_Cam1_Fronthousing\7_HKMC_SVS_Front
                if os.path.isdir(path_T):
                    folder_U = os.listdir(path_T)  # 列出文件夹所有文件
                    folder_list = []
                    for folder_uu in folder_U:  # 从名称中获取日期
                        folder_ymd = folder_uu[0:10]  # 2022-05-05
                        try:  # 尝试将文件夹名字划分为日期，不符合要求将忽略
                            dayfolder = time.strptime(folder_ymd, '%Y-%m-%d')
                        except ValueError:
                            print(
                                "%s\'is an unvalid folder name,not MATCH date format,will be IGNORED"
                                % (folder_ymd)
                            )
                            continue
                        folderexistday = (
                            (daytoday.tm_year - dayfolder.tm_year) * 366
                            + daytoday.tm_yday
                            - dayfolder.tm_yday
                        )  # 存在的天数
                        if folderexistday > 7:
                            if folder_ymd not in folder_list:
                                folder_list.append(folder_ymd)
                    for folder_ll in folder_list:
                        if i > i_max - 1:
                            break
                        new_Path = os.path.join(
                            dir,
                            Name_Type,
                            folder_ll[0:4],
                            Name_Type + "-" + folder_ll[0:10] + "-" + Name_FB,
                        )
                        temp_Path = os.path.join(
                            new_Path, folder_ll[0:10] + "-" + Name_FB
                        )
                        Path(temp_Path).mkdir(parents=True, exist_ok=True)
                        for folder_uu in folder_U:
                            if folder_uu[0:10] == folder_ll:
                                oldpath = os.path.join(path_T, folder_uu)
                                shutil.move(oldpath, temp_Path)
                        size = len(folder_lis)
                        folder_lis.append(folder_dir())
                        folder_lis[size].new_Path = new_Path
                        folder_lis[size].root = (
                            folder_tt
                            + "-"
                            + Name_Type
                            + "-"
                            + folder_ll[0:10]
                            + "-"
                            + Name_FB
                        )
                        folder_lis[size].Temp_path = temp_Path
                        i += 1

    # print(file_paths)
    return folder_lis


def main():
    directory = r'C:\MyTestResults\BH_assy'
    # directory = r'D:\Gen6 Test Result\BH_assy'
    sevenza_path = r'C:\MyCodeSpace\Python\FileAutoZip\7z2201-extra\7za.exe'
    # sevenza_path = r'C:\Users\DVS_ADMIN\Desktop\Taoxi\FileAutoZip\7z2201-extra\7za.exe'
    day_folder_List = get_all_folder(directory)
    count = 0  # 计算压缩的文件数量
    for folder in day_folder_List:
        # name with zip time
        newpath = (
            folder.new_Path
            + "-"
            + time.strftime("%y%m%d%H%M%S", time.localtime(int(time.time())))
            + ".7z"
        )
        # Zip File
        try:
            cmd = (
                "cmd /c \"\""
                + sevenza_path
                + "\" a  -bsp2 -mmt2 \""
                + newpath
                + "\" \""
                + folder.Temp_path
                + "\"\""
            )
            os.system(cmd)
        except:
            print("----------\"" + folder.Temp_path + "\"" + " Zip Failed!----------")
        else:
            print("----------\"" + folder.Temp_path + "\"" + " Zipped!----------")
            # delete zipped file
            shutil.rmtree(folder.new_Path)
            count += 1

    if count == 0:
        print("----------\" No file ready to zip! \"----------")
    else:
        print(
            "----------\" %d file%s zipped successfully!\" Zipped!----------"
            % (count, "s" * (count > 1))
        )


if __name__ == "__main__":
    main()
